package aar.test.tessocr;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.utils.Utils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.callback.StringCallback;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;

/**
 * Created by sunshine on 2020/9/24
 */
public class RegisterActivity extends BaseActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.et_phone_num)
    EditText etPhoneNum;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_captcha)
    EditText etCaptcha;
    @BindView(R.id.tv_send_captcha)
    TextView tvSendCaptcha;
    @BindView(R.id.rl_captcha)
    RelativeLayout rlCaptcha;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {

    }

    @OnClick({R.id.back, R.id.tv_send_captcha, R.id.grid_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_send_captcha:
                if (etPhoneNum.getText().toString().equals("") || !Utils.isMobile(etPhoneNum.getText().toString()) || etPhoneNum.getText().toString().length() != 11) {
                    Toast.makeText(RegisterActivity.this, "请输入有效的手机号码！", Toast.LENGTH_SHORT).show();
                    return;
                }

                tvSendCaptcha.setEnabled(false);
                Map<String ,Object> map=new HashMap<>();
                map.put("phone",etPhoneNum.getText().toString().trim());

                Gson gg=new Gson();
                String json =gg.toJson(map);

                RequestBody body = RequestBody.create(JSON,json);
                OkGo.<LzyResponse<String>>post(Urls.URL_YZM)//
                        .tag(this)//
                        .upRequestBody(body)
                        .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                        .execute(new DialogCallback<LzyResponse<String>>(RegisterActivity.this) {
                            @Override
                            public void onSuccess(Response<LzyResponse<String>> response) {
                                timer.start();
                                Toast.makeText(RegisterActivity.this, "验证码发送成功！", Toast.LENGTH_SHORT);
                            }

                            @Override
                            public void onError(Response<LzyResponse<String>> response) {
                                Toast.makeText(RegisterActivity.this, "验证码发送失败！", Toast.LENGTH_SHORT).show();
                            }
                        });
                break;
            case R.id.grid_edit:
                if (etPhoneNum.getText().toString().equals("") || !Utils.isMobile(etPhoneNum.getText().toString()) || etPhoneNum.getText().toString().length() != 11) {
                    Toast.makeText(RegisterActivity.this, "请输入有效的手机号码！", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (etCaptcha.getText().toString().equals("")) {
                    Toast.makeText(RegisterActivity.this, "请输入验证码！", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (etPassword.getText().toString().equals("")) {
                    Toast.makeText(RegisterActivity.this, "请输入密码！", Toast.LENGTH_SHORT).show();
                    return;
                }


                tvSendCaptcha.setEnabled(false);
                Map<String ,Object> map1=new HashMap<>();
                map1.put("phone",etPhoneNum.getText().toString().trim());
                map1.put("code",etCaptcha.getText().toString().trim());
                map1.put("password", etPassword.getText().toString().trim());
                map1.put("type", "1");

                Gson gg1=new Gson();
                String json1 =gg1.toJson(map1);

                RequestBody body1 = RequestBody.create(JSON,json1);
                OkGo.<String>post(Urls.URL_REGISTER)//
                        .tag(this)//
                        .upRequestBody(body1)
                        .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                /*Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT);
                                PrefUtils.setString(RegisterActivity.this, "userName", etPhoneNum.getText().toString().trim());
                                PrefUtils.setString(RegisterActivity.this, "password", "");
                                finish();*/

                                try {
                                    JSONObject jsonObject = new JSONObject(response.body());
                                    if (jsonObject.has("code")) {
                                        String code = jsonObject.getString("code");
                                        if (TextUtils.equals(code, "200")) {
                                            String msg = jsonObject.getString("msg");
                                            Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
                                        } else if (TextUtils.equals(code, "100")) {
                                            String msg = jsonObject.getString("msg");
                                            Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
                                            PrefUtils.setString(RegisterActivity.this, "userName", etPhoneNum.getText().toString().trim());
                                            PrefUtils.setString(RegisterActivity.this, "password", "");
                                            finish();
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                Toast.makeText(RegisterActivity.this, "注册失败！", Toast.LENGTH_SHORT);
                            }
                        });
                break;
        }
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvSendCaptcha.setText(millisUntilFinished / 1000 + "S");
            //tvSendCaptcha.setTextColor(getResources().getColor(R.color.text_white_50));
        }

        @Override
        public void onFinish() {
            tvSendCaptcha.setEnabled(true);
            tvSendCaptcha.setText(getResources().getString(R.string.mine_send_verify_code));
            //tvSendCaptcha.setTextColor(getResources().getColor(R.color.text_light_orange));
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
